/*
 * @Author: luojianfeng
 * @Date: 2022-12-16 11:15:47
 * @LastEditTime: 2023-01-10 09:47:52
 * @LastEditors: luojianfeng
 * @Description:
 */
import qs from 'qs'
//下载文件流
export function downloadFile(resBlob: any, name?: string) {
  const blob = new Blob([
    typeof resBlob.slice === 'function' ? resBlob : resBlob.data
  ])
  console.log(resBlob, name || resBlob?.fileName, 'download file data...')
  const eLink = document.createElement('a')
  eLink.style.display = 'none'
  eLink.setAttribute('download', name || resBlob?.fileName)
  eLink.href = URL.createObjectURL(blob)
  document.body.appendChild(eLink)
  eLink.click()
  URL.revokeObjectURL(eLink.href) // 释放URL 对象
  document.body.removeChild(eLink)
}

/**
 * 递归查找
 * @param list
 * @param fn
 * @param childName
 * @returns
 */
export const deepFind = (
  list: any[],
  fn: (e: any) => boolean,
  childName = 'children'
) => {
  const res: any[] = []
  const traverse = function (node: any[]) {
    node.forEach((item: any) => {
      if (fn(item)) {
        res.push(item)
      } else {
        item[childName] && traverse(item[childName])
      }
    })
  }
  traverse(list)
  return res
}

//文件转base64
export const getBase64 = (file: Blob) => {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader()
    let imgResult = ''
    reader.readAsDataURL(file)
    reader.onload = function () {
      imgResult = reader.result as any
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(imgResult)
    }
  })
}
//文件内容读取
export const getFileContent = (file: Blob) => {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader()
    let textResult = ''
    reader.readAsText(file as Blob, 'UTF-8')

    reader.onload = function (e) {
      textResult = e.target?.result as any
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(textResult)
    }
  })
}

/**
 * 获取 url 参数
 * @param {string} url 'http://baidu.com?id=1&name=laowang'
 * @returns 出参 { id: 1, name: 'laowang' }
 */
export const getUrlParams = (url: string) => {
  const index = url.indexOf('?')
  if (index === -1) return {}
  const params = url.slice(index + 1)
  return qs.parse(params)
}

export const getLocationPath = () => {
  const urls = window.location.href
  const arr = urls.split('/')
  return arr[3] || ''
}

export const judgeEnvAndGetPath = (type: 'ws' | 'download') => {
  const wsurl =
    import.meta.env.VITE_USER_NODE_ENV === 'development'
      ? import.meta.env.VITE_WS_URL
      : `${window.location.host}/${getLocationPath()}`
  const downloadUrl =
    import.meta.env.VITE_USER_NODE_ENV === 'development'
      ? import.meta.env.VITE_PROXY_URL
      : `${window.location.origin}/${getLocationPath()}`
  return type === 'ws' ? wsurl : downloadUrl
}
